-- msg_zlib_msg
-- Create by weism
-- 压缩后的消息
local zlib = require "zlib";

return function(lpc)
    local body = lpc.buf;
    local offset = 1;
    local raw;

    -- 解包出来
    if not USE_CPP_PACKER then
        body = Buffer.create(body);
        if Buffer.getu32(body, 1) == 0 then
            -- 服务器压缩失败了，直接复制数据(忽略前面4个字节)
            raw = Buffer.sub(body, 5, -1);
        else
            -- 解压出来
            body = Buffer.sub(body, 5, -1);
            raw = zlib.decompress(Buffer.byte(body));
            raw = Buffer.create(raw);
        end

        local cmdNo = Buffer.getu16(raw, offset);
        offset = offset + 2;

        -- 解包
        local now = socket.gettime();
        local v = PktAnalyser.unpack(cmdNo, Buffer.sub(raw, offset, -1));
        Profiler.addUnpack(cmdNo, socket.gettime() - now);
        if not v then
            cclog("解包失败了。");
        else
            -- 仍到队列中
            MSG.addMsgFirst(cmdNo, v);
        end
    else
        if body.byte(1) == 0 and body.byte(2) == 0 and body.byte(3) == 0 and body.byte(4) == 0 then
            -- 服务器压缩失败了，直接复制数据(忽略前面4个字节)
            raw = string.sub(body, 5);
        else
            -- 解压出来
            body = string.sub(body, 5);
            raw = zlib.decompress(body);
        end

        local cmdNo = 0
        for i = 1, 2 do
            cmdNo = cmdNo * 256 + string.byte(raw, i);
        end

        -- 解包
        local now = socket.gettime();
        local v = unpack_message(cmdNo, raw, 2);
        Profiler.addUnpack(cmdNo, socket.gettime() - now);
        if not v then
            cclog("解包失败了。");
        else
            -- 仍到队列中
            MSG.addMsgFirst(cmdNo, v);
        end
    end
end
